/*
 * Copyright (C) 2021 The Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.oushangfeng.pinneddemo.slice;

import com.oushangfeng.pinneddemo.ResourceTable;
import com.oushangfeng.pinneddemo.adapter.CategoryListItemProvider;
import com.oushangfeng.pinneddemo.adapter.CommonProvider;
import com.oushangfeng.pinneddemo.base.BaseAbilitySlice;
import com.oushangfeng.pinneddemo.butterknife.Bind;
import com.oushangfeng.pinneddemo.custom.data.CustomData;
import com.oushangfeng.pinneddemo.custom.data.GridLayoutData;
import com.oushangfeng.pinneddemo.custom.data.WaterfallFlowData;
import com.oushangfeng.pinneddemo.spinner.MaterialSpinner;
import com.oushangfeng.pinneddemo.util.ToastUtil;
import com.oushangfeng.pinnedsectionitemdecoration.callback.datainterface.Model;
import com.oushangfeng.pinnedsectionitemdecoration.callback.move.MoveMethod;

import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.Image;
import ohos.agp.components.ListContainer;
import ohos.agp.components.Text;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;

/**
 * MainAbilitySlice main class
 *
 * @since 2021-03-27
 */
public class MainAbilitySlice extends BaseAbilitySlice {
    private static final int UPSCROLL = 1;
    private static final int DOWNSCROLL = 2;
    private static final String[] SPIN_MUNE = {"线性布局", "网格布局", "瀑布流布局", "股价demo", "小标签demo"};

    private static final int FLAG = 2131558408;
    private static final int INTLINEAR = 0;
    private static final int INTGRIDE = 1;
    private static final int INTSTAGGERED = 2;
    private static final int INTSHARED = 3;
    private static final int INTLITTETITLE = 4;

    private static final int NUM_9 = 9;
    private static final int NUM_10 = 10;

    @Bind(ResourceTable.Id_show_header_item_content_text)
    private Text mShowHeaderItemContentText;

    @Bind(ResourceTable.Id_main_dependent)
    private DependentLayout mDependentLayout;

    @Bind(ResourceTable.Id_show_header_item_icon)
    private Image mShowHeaderItemImage;

    private ToastUtil toastUtil;

    private int scrollType = 0;

    private MainAbilitySlice context;
    private ListContainer listContainer;

    // onTouchEvent事件中记录down时的Y轴值
    private float mDownY = 0;

    private MoveMethod moveMethod;

    private int listSize = NUM_10;

    private int littleSize = NUM_9;

    private int cacheLayoutId = MoveMethod.LINEARLAYOUT;

    private MaterialSpinner spinner;

    // 记录布局
    private int layoutId = MoveMethod.LINEARLAYOUT;

    private boolean isDoubleClick = true;

    private CustomData customData = new CustomData();

    @Override
    public int getLayout() {
        return ResourceTable.Layout_ability_main;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        context = MainAbilitySlice.this;
        initMenu();
        initview();
        selectLayout(0);
    }

    private void initview() {
        toastUtil = new ToastUtil(this);

        listContainer = (ListContainer) findComponentById(ResourceTable.Id_list_view);

        mDependentLayout.setClipEnabled(true);

        moveMethod = new MoveMethod(listContainer, mShowHeaderItemContentText, mShowHeaderItemImage);

        moveMethod.setListSize(listSize);

        moveMethod.setLittleSize(littleSize);

        setDoubleClickedListener();

        setLongClickedListener();

        setClickedListener();

        setItemLongClickedListener();

        setItemClickedListener();

        setScrolledListener();

        setTouchEventLisener();

        initLinearLayout();
    }

    private void setTouchEventLisener() {
        listContainer.setTouchEventListener(new Component.TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                int action = touchEvent.getAction();
                MmiPoint point = touchEvent.getPointerPosition(touchEvent.getIndex());
                switch (action) {
                    case TouchEvent.PRIMARY_POINT_DOWN:
                        return true;
                    case TouchEvent.POINT_MOVE:
                        isDoubleClick = false;
                        if (point.getY() > mDownY) {
                            scrollType = UPSCROLL;
                        } else if (point.getY() < mDownY) {
                            // 下滑事件
                            scrollType = DOWNSCROLL;
                        }
                        mDownY = point.getY();
                        break;
                    case TouchEvent.PRIMARY_POINT_UP:
                        mDownY = 0;
                        isDoubleClick = true;
                        break;
                    case TouchEvent.NONE:
                    case TouchEvent.CANCEL:
                        mDownY = point.getY();
                        return true;
                    default:
                        break;
                }
                return false;
            }
        });
    }

    private void setScrolledListener() {
        listContainer.setScrolledListener(new Component.ScrolledListener() {
            @Override
            public void onContentScrolled(Component component, int i, int i1, int i2, int i3) {
                if (scrollType == UPSCROLL) {
                    moveMethod.upMove();
                } else if (scrollType == DOWNSCROLL) {
                    moveMethod.downMove();
                }
            }
        });
    }

    private void setItemClickedListener() {
        // 单击事件
        listContainer.setItemClickedListener((mlistContainer, component, position, l) -> {
            int listItem = moveMethod.getListItem(position);
            int listNum = moveMethod.getListNum(position);

            int mLittleListItem = moveMethod.getLittleListItem(position);
            int mLittleListNum = moveMethod.getLittleListNum(position);

            long itemId = listContainer.getItemProvider().getItemId(position);

            if (moveMethod.getLayoutId() == moveMethod.LINEARLAYOUT) {
                int type = moveMethod.getCategoryListDatas().get(listItem).getCategoryItemType(listNum);
                String itemVaule = moveMethod.getCategoryListDatas().get(listItem).getItemVaule(0);
                if (type == moveMethod.HEADITEM_ITEM_TYPE) {
                    toastUtil.toast(MainAbilitySlice.this, "item click,tag: " + itemVaule);
                } else {
                    toastUtil.toast(MainAbilitySlice.this, "item click :"
                            + itemVaule + ",position " + position + ",id " + itemId);
                }
            } else if (moveMethod.getLayoutId() == moveMethod.GRIDELAYOUT
                    || moveMethod.getLayoutId() == moveMethod.STAGGEREDGRIDKAYOUT) {
                String itemValue = moveMethod.getModels().get(position).getItemValue();
                int type = moveMethod.getModels().get(position).getItemType();
                if (type == moveMethod.HEADITEM_ITEM_TYPE) {
                    toastUtil.toast(MainAbilitySlice.this, "item click,tag: " + itemValue);
                } else {
                    toastUtil.toast(MainAbilitySlice.this, "item click :"
                            + itemValue + ",position " + position + ",id " + itemId);
                }
            } else if (moveMethod.getLayoutId() == moveMethod.LITTLETITLELAYOUT) {
                String itemVaule = moveMethod.getCategoryListDatas()
                        .get(mLittleListItem)
                        .getItemName(mLittleListNum);
                toastUtil.toast(MainAbilitySlice.this, itemVaule + ",position " + position + ",id " + itemId);
            }
        });
    }

    private void setItemLongClickedListener() {
        listContainer.setItemLongClickedListener((mlistContainer, component, position, l) -> {
            int listItem = moveMethod.getListItem(position);
            int listNum = moveMethod.getListNum(position);
            long itemId = listContainer.getItemProvider().getItemId(position);
            if (moveMethod.getLayoutId() == moveMethod.LINEARLAYOUT) {
                int type = moveMethod.getCategoryListDatas().get(listItem).getCategoryItemType(listNum);
                String itemVaule = moveMethod.getCategoryListDatas().get(listItem).getItemVaule(0);
                if (type == moveMethod.HEADITEM_ITEM_TYPE) {
                    toastUtil.toast(MainAbilitySlice.this, "item long click,tag: " + itemVaule);
                } else {
                    toastUtil.toast(MainAbilitySlice.this, "item long click :"
                            + itemVaule + ",position " + position + ",id " + itemId);
                }
            } else if (moveMethod.getLayoutId() == moveMethod.GRIDELAYOUT
                    || moveMethod.getLayoutId() == moveMethod.STAGGEREDGRIDKAYOUT) {
                String typeName = moveMethod.getModels().get(position).getTypeName();
                String itemValue = moveMethod.getModels().get(position).getItemValue();
                int itemType = moveMethod.getModels().get(position).getItemType();
                if (itemType == moveMethod.HEADITEM_ITEM_TYPE) {
                    toastUtil.toast(MainAbilitySlice.this, "item long click,tag:" + itemValue);
                } else {
                    toastUtil.toast(MainAbilitySlice.this, "item long click :" + typeName
                            + ",position " + position + ",id " + itemValue);
                }
            }
            return true;
        });
    }

    private void setClickedListener() {
        mShowHeaderItemImage.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                toastUtil.toast(MainAbilitySlice.this, "click,tag: " + moveMethod.getmLittleItem());
            }
        });

        mShowHeaderItemContentText.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                toastUtil.toast(MainAbilitySlice.this, "click,tag: " + mShowHeaderItemContentText.getText());
            }
        });
    }

    private void setLongClickedListener() {
        mShowHeaderItemContentText.setLongClickedListener(new Component.LongClickedListener() {
            @Override
            public void onLongClicked(Component component) {
                toastUtil.toast(MainAbilitySlice.this, "long click,tag: " + mShowHeaderItemContentText.getText());
            }
        });
    }

    private void setDoubleClickedListener() {
        mShowHeaderItemContentText.setDoubleClickedListener(new Component.DoubleClickedListener() {
            @Override
            public void onDoubleClick(Component component) {
                if (moveMethod.getLayoutId() == moveMethod.GRIDELAYOUT
                        || moveMethod.getLayoutId() == moveMethod.STAGGEREDGRIDKAYOUT
                        || moveMethod.getLayoutId() == MoveMethod.LINEARLAYOUT) {
                    toastUtil.toast(context, "click, tag:" + mShowHeaderItemContentText.getText());
                }
                toastUtil.toast(context, "这就是传说中的双击事件");
            }
        });

        listContainer.setDoubleClickedListener(new Component.DoubleClickedListener() {
            @Override
            public void onDoubleClick(Component component) {
                if (isDoubleClick) {
                    doubleClick();
                }
            }
        });
    }

    private void doubleClick() {
        toastUtil.toastCtx(context, "这就是传说中的双击事件");
    }

    @Override
    protected void initData() {
        super.initData();
    }

    // 线性
    private void initLinearLayout() {
        // 获取适配list
        moveMethod.setListDatas(customData.getCustomData(context));
        moveMethod.setCacheListDatas(customData.getCustomData(context));
        CategoryListItemProvider categoryListItemProvider
                = new CategoryListItemProvider(moveMethod.getCategoryListDatas());

        if (listContainer != null) {
            listContainer.setItemProvider(categoryListItemProvider);
        }

        mShowHeaderItemImage.setVisibility(Component.HIDE);
    }

    // 网格
    private void initGridsList() {
        GridLayoutData gridLayoutData = new GridLayoutData(context);
        moveMethod.setListModels(gridLayoutData.getData());
        moveMethod.setCacheListModels(gridLayoutData.getData());
        listContainer.setItemProvider(
                new CommonProvider<Model>(
                        moveMethod.getModels(), context));
    }

    // 瀑布
    private void initWaterfallFlow() {
        WaterfallFlowData waterfallFlowData = new WaterfallFlowData(context);
        moveMethod.setListModels(waterfallFlowData.getData());
        moveMethod.setCacheListModels(waterfallFlowData.getData());
        listContainer.setItemProvider(
                new CommonProvider<Model>(
                        moveMethod.getModels(), context));
    }

    // 股价demo
    private void initSharesDemo() {
        nextPage("com.oushangfeng.pinneddemo.ability.SharesDemoAbility");
    }

    private void initSmallLabel() {
        // 获取适配list
        moveMethod.setListDatas(customData.getSmallLabelData(context));
        moveMethod.setCacheListDatas(customData.getSmallLabelData(context));
        CategoryListItemProvider categoryListItemProvider
                = new CategoryListItemProvider(moveMethod.getCategoryListDatas());
        if (listContainer != null) {
            listContainer.setItemProvider(categoryListItemProvider);
        }
    }

    private void nextPage(String pageName) {
        // 指定待启动FA的bundleName和abilityName
        Intent secondIntent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName("com.oushangfeng.pinneddemo")
                .withAbilityName(pageName)
                .build();
        secondIntent.setOperation(operation);
        startAbility(secondIntent);
    }

    // 菜单
    private void initMenu() {
        spinner = (MaterialSpinner) findComponentById(ResourceTable.Id_main_spinner);
        spinner.setItems(SPIN_MUNE);
        spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
            @Override
            public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                selectLayout(position);
                spinner.setShowFalse();
            }
        });
        spinner.setOnNothingSelectedListener(new MaterialSpinner.OnNothingSelectedListener() {
            @Override
            public void onNothingSelected(MaterialSpinner mspinner) {
                mspinner.setShowFalse();
            }
        });
    }

    // 点击选择
    private void selectLayout(int i) {
        moveMethod.setText("Dog");
        moveMethod.setCacheTitle("Dog");
        moveMethod.setPixelMap(ResourceTable.Media_dog0);
        mShowHeaderItemImage.setVisibility(Component.HIDE);
        mShowHeaderItemContentText.setVisibility(Component.VISIBLE);
        switch (i) {
            case INTLINEAR:
                if (moveMethod.getLayoutId() != MoveMethod.LINEARLAYOUT) {
                    cacheLayoutId = MoveMethod.LINEARLAYOUT;
                    moveMethod.setLayoutId(MoveMethod.LINEARLAYOUT);
                    initLinearLayout();
                }

                break;
            case INTGRIDE:
                if (moveMethod.getLayoutId() != MoveMethod.GRIDELAYOUT) {
                    cacheLayoutId = MoveMethod.GRIDELAYOUT;
                    moveMethod.setLayoutId(MoveMethod.GRIDELAYOUT);
                    initGridsList();
                }

                break;
            case INTSTAGGERED:
                if (moveMethod.getLayoutId() != MoveMethod.STAGGEREDGRIDKAYOUT) {
                    cacheLayoutId = MoveMethod.STAGGEREDGRIDKAYOUT;
                    moveMethod.setLayoutId(MoveMethod.STAGGEREDGRIDKAYOUT);
                    initWaterfallFlow();
                }
                break;
            case INTSHARED:
                if (moveMethod.getLayoutId() != MoveMethod.SHAREDLAYOUT) {
                    moveMethod.setLayoutId(MoveMethod.SHAREDLAYOUT);
                    initSharesDemo();
                }
                break;
            case INTLITTETITLE:
                if (moveMethod.getLayoutId() != MoveMethod.LITTLETITLELAYOUT) {
                    moveMethod.setLayoutId(MoveMethod.LITTLETITLELAYOUT);
                    mShowHeaderItemImage.setVisibility(Component.VISIBLE);
                    mShowHeaderItemContentText.setVisibility(Component.HIDE);
                    moveMethod.setCacheTitle(ResourceTable.Media_dog0 + "");
                    spinner.setVisibility(Component.HIDE);
                    initSmallLabel();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onBackPressed() {
        if (moveMethod.getLayoutId() == MoveMethod.LITTLETITLELAYOUT) {
            spinner.setVisibility(Component.VISIBLE);
            if (cacheLayoutId == MoveMethod.LINEARLAYOUT) {
                selectLayout(INTLINEAR);
            } else if (cacheLayoutId == MoveMethod.GRIDELAYOUT) {
                selectLayout(INTGRIDE);
            } else if (cacheLayoutId == MoveMethod.STAGGEREDGRIDKAYOUT) {
                selectLayout(INTSTAGGERED);
            }
        } else {
            super.onBackPressed();
        }
    }
}
